package org.tinygroup.channel.protocol.impl;

import java.util.ArrayList;
import java.util.List;

import org.tinygroup.channel.protocol.ProtocolListener;
import org.tinygroup.context.Context;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;

public class ProtocolListenerChain {
	private final static Logger LOGGER = LoggerFactory.getLogger(ProtocolListenerChain.class);
	private List<ProtocolListener<?,?>> list = new ArrayList<ProtocolListener<?,?>>();
	private int size=0;
	private int currentPrePosition = 0;
	private int currentPostPosition = 0;
	public ProtocolListenerChain(List<ProtocolListener<?,?>> list) {
		this.list = list;
		if(list!=null&&!list.isEmpty()){
			this.size = list.size();
		}
		
	}
	
	public void pre(Object request,Context context){
        if (currentPrePosition < size) {
        	ProtocolListener nextLisenter = list.get(currentPrePosition);
        	LOGGER.logMessage(LogLevel.DEBUG, "firing ProtocolListener PRE :'{}'", nextLisenter
                    .getClass().getSimpleName());
        	currentPrePosition++;
            nextLisenter.pre(request,context,this);
        }
    }

	@SuppressWarnings("rawtypes")
	public void post(Object request,Object response,Context context){
        if (currentPostPosition < size) {
        	ProtocolListener nextLisenter = list.get(currentPostPosition);
        	LOGGER.logMessage(LogLevel.DEBUG, "firing ProtocolListener POST :'{}'", nextLisenter
                    .getClass().getSimpleName());
        	currentPostPosition++;
            nextLisenter.post(request,response,context,this);
        }
    }
	
}
